<style>
    /*数据表格内容换行显示*/
    .layui-table-cell {
        height: auto;
        /*空白会被浏览器忽略*/
        white-space: normal;
        /*允许长单词换行到下一行*/
        word-wrap: break-word;
        /*允许在单词内换行*/
        word-break: break-all;
    }
</style>
<div class="layui-card-header layui-card">
    <span class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">首页</a>
        <a><cite class="cite1"></cite></a>
        <a><cite class="cite2"></cite></a>
    </span>
</div>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li class="layui-this">子账户列表</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <div class="layui-row">
                        <div class="layuiAdmin-btns layui-input-inline" style="margin-bottom: 10px;">
                            <a class="layui-btn add" data-type="all" data-events="create"><i class="layui-icon layui-icon-add-1"></i>新增账户</a>
                            <a class="layui-btn layui-btn-danger" data-type="del" data-events="del" id="del"><i class="layui-icon layui-icon-delete"></i>彻底删除</a>
                        </div>
                        <div class="layui-form" style="float:right; margin-bottom: 10px;">
                            <div class="layui-form-item" style="margin:0;">
                                <div class="layui-input-inline">
                                    <select name="searchStatus" id="searchStatus" lay-search="">
                                        <option value="-99">账户状态</option>
                                        <option value="1">开启</option>
                                        <option value="0">关闭</option>
                                    </select>
                                </div>
                                <a id="search" class="layui-btn" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>
                            </div>
                        </div>
                    </div>
                </div>
                    <table id="cList" lay-filter="cList"></table>
            </div>
        </div>
    </div>
</div>
<script>
    layui.use(['table','util', 'form','admin'], function(){
        var table = layui.table
        ,$ = layui.$
        ,form = layui.form
        ,element = layui.element
        ,view = layui.view
        ,admin = layui.admin;

        var refPageType = $("#refPageType").val();
        //处理页面不同样式
        if(refPageType == 1){ //子账号列表
            $(".cite1").text('账号列表');$(".cite2").text('');
            $('.addAccountDiv').hide();
            $('.add').hide();
        }else{  //支付通道_通道子账号配置（原页面）
            $(".cite1").text('支付通道');$(".cite2").text('子账户');
            $('.updateAccountState').hide();
        }

        element.render('breadcrumb', 'breadcrumb');//渲染导航信息

        var router = layui.router();
        var payPassageId = router.search.payPassageId;

        var configType = ""; //配置类型

        var tplEdit = function(d){

            var appendHtml ="";
            if(d.IfCode == 'alipay_qr_pc' || d.IfCode == 'alipay_qr_h5'){
                appendHtml = "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='coll'><i class='layui-icon layui-icon-set-sm'></i>分账配置</a>";
            }

            return "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='risk'><i class='layui-icon layui-icon-engine'></i>风控</a>" +
                appendHtml +
                "<a class='layui-btn layui-btn-warm layui-btn-xs' lay-event='test'><i class='layui-icon layui-icon-link'></i>接口检测</a>"+
                "<a class='layui-btn layui-btn-xs' lay-event='edit'><i class='layui-icon layui-icon-edit'></i>编辑</a>";
        };

        var tplRate = function(d){
            return "<span style='color: blue'>"+ d.passageRate+"%</span>";
        };

        var tplDatas = function(d){
            var todayHtml = "今日 ：成功金额：" + d.todayAmount/100 + "元，" + "成功笔数：" +d.todayCount+ "，成功率" +d.todaySuccessRate+ "<br/>";
            var yestdayHtml = "昨日 ：成功金额：" + d.yestdayAmount/100 + "元，" + "成功笔数：" +d.yestdayCount+ "，成功率" +d.yestdaySuccessRate+ "<br/>";
            var allHtml = "全部 ：成功金额：" + d.totalAmount/100 + "元，" + "成功笔数：" +d.totalCount+ "，成功率" +d.successRate+ "<br/>";
            return todayHtml+yestdayHtml+allHtml;
        };
        var tplStatus = function(d){
            if(d.status == 0) {
                return '<input type="checkbox" name="checkStatus" lay-skin="switch" value= "'+d.id+","+d.status+'" lay-filter="switch" lay-text="开启|关闭">';
            }else if(d.status == 1) {
                return '<input type="checkbox" name="checkStatus" lay-skin="switch" value= "'+d.id+","+d.status+'" lay-filter="switch" lay-text="开启|关闭" checked>';
            }
        };

        //监听指定开关
        form.on('switch(switch)', function(data){
            var ids = [];
            var value = data.value.split(",");
            ids.push(value[0].trim());
            var state = value[1].trim();
            admin.req({
                type: 'post',
                url: layui.setter.baseUrl + '/config/pay_passage_account/updateState',
                data: {
                    ids : JSON.stringify(ids),
                    state : state
                },
                error: function(err){layer.alert(err.msg,{title:"请求失败"})},
                success: function(res){
                    if(res.code == 0){
                        layer.msg('修改成功！');
                    }
                }
            })
        });

        var tplTestStatus = function(d){
            if(d.testStatus == 0) {
                return "<span>接口未检测</span>";
            }else if(d.testStatus == 1){
                return "<span style='color: green'>检测通过</span>";
            }else {
                return "<span style='color: red'>检测未通过</span>";
            }
        };

        var isOnlySupplierParam = "";
        if(refPageType == 1){ //MS子账号列表 只查询MS的子账号
            isOnlySupplierParam = "true";
        }

        table.render({
            elem: '#cList'
            ,url: layui.setter.baseUrl + '/config/pay_passage_account/list'
            ,where: { access_token: layui.data(layui.setter.tableName).access_token, payPassageId: payPassageId, "ps[isOnlySupplier]" : isOnlySupplierParam}
            ,id: 'tableReload'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', width:100, title: '账户ID'}
                ,{field:'accountName', width:140, title: '账户名称'}
                /*,{field:'IfCode', title: '接口代码', align:'center'}
                ,{field:'IfName', title: '接口名称', align:'center'}*/
                ,{field:'passageRate', width:100, title: '通道费率', templet: tplRate}
                // ,{field:'datas',title: '账户数据',align:'center', templet: tplDatas, width: 400}
                ,{title: '账户状态',templet: tplStatus }
                ,{title: '最后一次检测状态',templet: tplTestStatus }
                ,{fixed:'right',field:'edite', align:'center', title: '操作', templet: tplEdit,  width: 300}
            ]]
            ,page: true
            ,skin: 'line'
            ,done: function () {
                autoFixed($(this.elem[0]).next());
            }
        });

        //监听工具条
        table.on('tool(cList)', function(obj){
            var data = obj.data;
            if(obj.event === 'risk'){
                view.xxpayPopup("风控", "config/pay_passage_account/risk_set", {id: data.id}, {area:["60%", "80%"]});
            }  else if(obj.event === 'edit'){

                if(data.configType == 1){
                    view.xxpayPopup("编辑", "config/pay_passage_account/update", {id: data.id});
                }else if(data.configType == 2){
                    view.xxpayPopup("编辑", "config/pay_passage_account/updateByTC", {id: data.id});
                }

            }else if(obj.event === 'coll'){
                location.href = layui.setter.baseLocal + "config/pay_passage_account/cash_coll_set/id=" + data.id;
            }else if(obj.event === 'test'){ //点击【接口验证】事件

                layer.confirm('接口验证将在上游生成一笔真实待支付订单（本系统内不保留），是否继续？', {
                    btn: ['继续验证','返回']
                }, function(){
                    //请等待，正在调起接口进行验证...
                    var layerMsgId = layer.msg('请等待，正在调起接口进行验证... ',{time: 0, shade: 0.3});

                    //发起测试
                    admin.req({
                        type: 'get',
                        url: layui.setter.baseUrl + '/config/pay_passage_account/channelTest',
                        data:{id: data.id},
                        error: function(err){layer.close(layerMsgId);layer.alert(err);},
                        success: function(res){
                            layer.close(layerMsgId); ///关闭弹层

                            if(res.code == 0){
                                layer.alert(res.msg);
                                table.reload('tableReload');
                            }else{
                                layer.alert("系统异常["+res.msg+"]");
                            }
                        }
                    });
                });
            }
        });

        // 事件处理
        var events = {
            create: function(othis, type){

                if(!configType){

                    //查询配置方式
                    admin.req({
                        type: 'post',
                        url: layui.setter.baseUrl + '/config/pay_passage/get',
                        async: false,
                        data: {id:payPassageId},
                        error: function(err){layer.alert(err);},
                        success: function(res){
                            configType = res.data.configType;
                        }
                    });
                }

                if(configType == 1){
                    view.xxpayPopup("新增账户", "config/pay_passage_account/create", {payPassageId: payPassageId});
                }else if(configType == 2){
                    view.xxpayPopup("新增账户", "config/pay_passage_account/createByTC", {payPassageId: payPassageId});
                }
            },
            del: function () { //获取选中数据
                var checkedData = table.checkStatus("tableReload").data; //获得选中的数据
                if(checkedData.length === 0) return layer.msg('请选择数据');
                var delIds = [];
                $.each(checkedData, function(){
                    delIds.push(this.id);
                });

                //弹层
                var relationDeleteHtml = `
                <div style="color:red; margin:20px; padding-left:50px" >
                    <label class="layui-inline"> 此操作将删除选中数据及所有关联数据！是否继续删除？</label><br/><br/>
                    <label class="layui-inline"> 关联表：[支付通道账户表];</label>
                </div>
                <form class="layui-form center">
                    <div class="layui-form-item" style="margin-top:30px">
                        <div class="layui-input-block" style="margin-left: 180px;">
                            <button type="button" class="layui-btn layui-btn-danger relationDeleteBtn">确认删除</button>
                            <button type="button" class="layui-btn layui-btn-normal" onclick="layer.closeAll();">取消</button>
                        </div>
                    </div>
                </form>
            `;
                //打开弹层
                var thisLayerId = layer.open({ type: 1, area: ['520px', 'auto'], title: '提示', content: relationDeleteHtml });
                $(".relationDeleteBtn").click(function(){

                    var layerMsgId = layer.msg('正在执行删除任务... ',{time: 0, shade: 0.3});
                    admin.securityReq({
                        type: 'get',
                        url: layui.setter.baseUrl + '/config/pay_passage_account/relationDelete',
                        data: {ids: JSON.stringify(delIds)},
                        error: function (err) {
                            layer.close(layerMsgId);
                            layer.alert(err);
                        },
                        success: function (res) {
                            layer.close(layerMsgId);
                            if(res.code == '0'){ //成功创建任务
                                layer.close(thisLayerId);
                                table.reload('tableReload');  //刷新页面
                                layer.alert("操作成功, 共删除了 "+res.data+" 条关联数据！");
                            }
                        },
                        complete: function () {

                        }
                    });
                });
            }
        };
        $('.layuiAdmin-btns .layui-btn').on('click', function(){
            var othis = $(this)
                    ,thisEvent = othis.data('events')
                    ,type = othis.data('type');
            events[thisEvent] && events[thisEvent].call(this, othis, type);
        });

        // 搜索
        var $ = layui.$, active = {
            reload: function(){
                var searchStatus = $("#searchStatus").val();
                //执行重载
                table.reload('tableReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        status : searchStatus
                    }
                });
            }
        };
        $('#search').on('click', function() {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //更新账户状态
        form.on('switch(switchStatus)', function (data) {
            var id = data.value;
            var status = this.checked ? '1' : '0';
            admin.req({
                type: 'post',
                url: layui.setter.baseUrl + '/config/pay_passage_account/update',
                data: {
                    id:  id,
                    status: status
                },
                error: function (err) {
                    layer.alert(err);
                },
                success: function (res) {
                    if (res.code == 0){
                        layer.msg('修改成功',{time:1000})
                    }else {
                        layer.msg('修改失败，请重试');
                    }
                }
            });
        });

        // 渲染表单
        form.render();

        /**
         * 根据表格宽度自动显示右侧浮动栏,并修正浮动栏高度
         * @param tableElem 绑定元素的dom
         */
        function autoFixed(tableElem) {
            var $tableView = tableElem || $(".layui-table-view");
            var dataIndex ,trHeight;
            $tableView.each(function() {
                // 获取两侧浮动栏
                var $fixed = $(this).find(".layui-table-fixed");
                // 同步表头高度
                $fixed.find(".layui-table-header tr").height($(this).find(".layui-table-header tr").eq(0).height());
                // 遍历tr 修正浮动栏行高
                $(this).find(".layui-table-main tr").each(function() {
                    dataIndex = $(this).attr("data-index");
                    trHeight = $(this).css("height");
                    $fixed.find("tr[data-index=" + dataIndex + "]").css("height", trHeight);
                })
            });
        }

        // 监听浏览器窗口大小变化
        var resizeTimer;
        $(window).resize(function() {
            if (resizeTimer) {
                clearTimeout(resizeTimer);
            }
            resizeTimer = setTimeout(function() {
                    resizeTimer = null;
                    autoFixed();
                },
                200);
        });

        // 监听表头鼠标按下事件
        $(document).on('mousedown', 'thead',
            function(e) {
                var that = $(this);
                $(document).one('mouseup',
                    function() {
                        autoFixed(that.parents('.layui-table-view'));
                    })
        });

    });
    
</script>
